package com.mcp_life.util;

import com.mcp_life.common.config.AliyunApiCredentialManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class AliyunApiUtils {

    @Autowired
    private AliyunApiCredentialManager credentialManager;

    /**
     * 发送实名认证请求到阿里云API
     *
     * @param idNumber 身份证号码
     * @param name 姓名
     * @return 响应结果
     */
    public String verifyIdentity(String idNumber, String name) {
        try {
            String host = "https://sinocheck2.market.alicloudapi.com";
            String path = "/verify/identity";
            String method = "POST";
            // 检查凭证是否配置
            if (!credentialManager.isConfigured()) {
                log.error("阿里云API凭证未配置完整");
                throw new RuntimeException("阿里云API凭证未配置完整");
            }

            // 设置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "APPCODE " + credentialManager.getAppCode());
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            // 空的查询参数
            Map<String, String> querys = new HashMap<>();

            // 设置Body参数
            Map<String, String> bodys = new HashMap<>();
            bodys.put("name", name);
            bodys.put("id_number", idNumber);

            log.info("准备发送实名认证请求到阿里云API，身份证: {}, 姓名: {}", idNumber, name);

            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);

            // 获取响应内容
            String result = EntityUtils.toString(response.getEntity());

            log.info("阿里云API请求成功，响应: {}", result);
            return result;
        } catch (Exception e) {
            log.error("阿里云API请求失败，身份证: {}, 姓名: {}, 错误详情: {}", idNumber, name, e.getMessage(), e);
            throw new RuntimeException("阿里云API请求失败: " + e.getMessage());
        }
    }
}
